package com.human.controller;

import com.human.entity.ResultVo;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author jzq
 * @date 2023/3/21 12:43
 */
@SuppressWarnings({"all"})
@RestController
@RequestMapping("/api")
@Api(tags = "文件上传")
public class UploadController {

    @PostMapping("/upload")
    public ResultVo upload(@RequestPart("file") MultipartFile file) throws IOException {
        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件扩展名
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        // 通过UUID构造唯一的文件名
        String newFileName = UUID.randomUUID().toString() + extname;
        // 将文件保存到本地
        String path = "E:/humanresources/src/main/resources/static/files/" + newFileName;
        file.transferTo(new File(path));
        return new ResultVo(true, "上传成功", path);
    }

}
